package com.cly.item.service.impl;

import cn.hutool.json.JSONUtil;
import com.aliyun.teautil.Common;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cly.common.content.ItemContent;
import com.cly.common.entity.category.po.Category;
import com.cly.common.entity.result.Result;
import com.cly.common.exception.CommonException;
import com.cly.item.mapper.CategoryMapper;
import com.cly.item.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Qualifier("threadPoolTaskExecutor")
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    /**
     * 获取所有分类
     * @return
     */
    @Override
    public Result getCategoryAll() {
        // 先从Redis换成中获取分类信息
        String categoryJson = stringRedisTemplate.opsForValue().get(ItemContent.CATEGORY_ALL_REDIS_KEY);
        //  判断是否存在缓存
        if (StringUtils.isNotBlank(categoryJson)) {
            // 存在缓存，转换成List集合返回
            List<Category> categoryList = JSONUtil.toList(categoryJson, Category.class);
            return Result.success(categoryList);
        }
        // 不存在缓存，从数据库中获取
        try {
            List<Category> categoryList = this.list();
            if(categoryList == null || categoryList.isEmpty()){
                throw new CommonException("获取分类失败");
            }
            // 数据库中存在数据，开心线程缓存到Redis中
            threadPoolTaskExecutor.submit(()->{
                stringRedisTemplate.opsForValue()
                        .set(ItemContent.CATEGORY_ALL_REDIS_KEY,JSONUtil.toJsonStr(categoryList),
                                ItemContent.CATEGORY_ALL_REDIS_KEY_EXPIRE, TimeUnit.MINUTES);
            });
            return Result.success(categoryList);
        } catch (Exception e) {
            throw new CommonException("获取分类失败",e);
        }
    }

    /**
     * 删除Redis缓存
     */
    @Override
    public void deleteCategoryRedis(){
        // 第一次删除缓存
        stringRedisTemplate.delete(ItemContent.CATEGORY_ALL_REDIS_KEY);
        // 开启线程，休眠0.5秒，进行第二次删除缓存
        threadPoolTaskExecutor.submit(()->{
            try {
                Thread.sleep(500);
                stringRedisTemplate.delete(ItemContent.CATEGORY_ALL_REDIS_KEY);
            } catch (InterruptedException e) {
                log.error("删除Redis缓存失败：", e);
                throw new CommonException(e);
            }
        });
    }
}
